﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;

namespace HB.WpfEx
{
    public static class WriteableBitmapEx
    {
        public static void UsingGraphics(this WriteableBitmap map, Action<Graphics> action)
        {
            map.Dispatcher.Invoke(() =>
            {
                if (map.Format == System.Windows.Media.PixelFormats.Bgr32 || map.Format == System.Windows.Media.PixelFormats.Bgr24)
                {
                    var bitmapfotmat = map.Format == System.Windows.Media.PixelFormats.Bgr32 ? System.Drawing.Imaging.PixelFormat.Format32bppPArgb : System.Drawing.Imaging.PixelFormat.Format24bppRgb;
                    using (var bmap = new Bitmap(map.PixelWidth, map.PixelHeight, map.BackBufferStride, bitmapfotmat, map.BackBuffer))
                    {
                        using (Graphics g = Graphics.FromImage(bmap))
                        {
                            map.Lock();
                            action.Invoke(g);
                            map.AddDirtyRect(new Int32Rect(0, 0, map.PixelWidth, map.PixelHeight));
                            map.Unlock();
                        }
                    }
                }
                else
                {
                    throw new Exception("only support bgr32 or bgr24");
                }
            });
        }
    }
}
